package com.adams.app.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.onekeyshare.OnekeyShare;

import com.adams.app.R;
import com.adams.app.common.Global;
import com.adams.app.dao.FoodsDateHelper;
import com.adams.app.data.GsonRequest;
import com.adams.app.data.RequestManager;
import com.adams.app.model.Food;
import com.adams.app.model.Food.FoodsRequestData;
import com.adams.app.ui.adapter.CardsAnimationAdapter;
import com.adams.app.ui.adapter.FoodsAdapter;
import com.adams.app.ui.view.LoadingFooter;
import com.adams.app.utils.CommonUtils;
import com.adams.app.vendor.HappyGyApi;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.haarman.listviewanimations.swinginadapters.AnimationAdapter;

/**
 * @description 美食列表
 * @author ChengBin
 * 
 */
public class FoodsActivity extends ActionBarActivity 
			implements LoaderManager.LoaderCallbacks<Cursor>,
			PullToRefreshAttacher.OnRefreshListener {

	private ListView foodListView;
	private FoodsAdapter foodAdapter;
	private FoodsDateHelper foodsDateHelper;
	private PullToRefreshAttacher mPullToRefreshAttacher;
	private LoadingFooter mLoadingFooter;
	private int mPage = 1;
	private String foodName;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_foods);
		
		foodName = getIntent().getStringExtra(Global.FOOD_NAME);
		initView();
		initData();
	}
	
	

	private void initView() {
		this.foodListView = (ListView) this.findViewById(R.id.foods_list);
		//刷新
		PullToRefreshAttacher.Options options = new PullToRefreshAttacher.Options();
		options.headerInAnimation = R.anim.pulldown_fade_in;
		options.headerOutAnimation = R.anim.pulldown_fade_out;
		options.refreshScrollDistance = 0.3f;
		options.headerLayout = R.layout.pulldown_header;
		mPullToRefreshAttacher = new PullToRefreshAttacher(this, options);
	}

	private void initData() {
		foodsDateHelper = new FoodsDateHelper(this, foodName);
		foodAdapter = new FoodsAdapter(this, foodListView);
			
		// 准备装载器
		getSupportLoaderManager().initLoader(0, null, this);
		
		View header = new View(this);
		
		// 下拉刷新
		mPullToRefreshAttacher.setRefreshableView(foodListView, this);
		
		// 脚部加载
		mLoadingFooter = new LoadingFooter(this);
		
		// listView添加控件
		foodListView.addHeaderView(header);
		foodListView.addFooterView(mLoadingFooter.getView());
		foodListView.setOnScrollListener(foodScrollListener);
		foodListView.setOnItemClickListener(itemClickListener);
		// 动画适配器
		AnimationAdapter animationAdapter = new CardsAnimationAdapter(foodAdapter);
		animationAdapter.setListView(foodListView);
		
		
		//设置Adapter
		foodListView.setAdapter(animationAdapter);	
		
	}

	
	/*************************************************
	 *           重写loader加载器方法                                     		 * 
	 *          									 *
	 *************************************************/
	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		return foodsDateHelper.getCursorLoader();
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		foodAdapter.changeCursor(data);		
		
		if (data != null && data.getCount() == 0) {
			loadFirstPage();
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		foodAdapter.changeCursor(null);
	} 
	//loader end
	
	
	private void loadFirstPage() {
		loadDataFromNet(1);
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onStop() {
		super.onStop();
		RequestManager.cancelAll(this);
	}
	
	
	/**
	 * 
	 * @description 从网络加载数据,请求数据
	 * 
	 * @author ChengBin
	 * @param url
	 * @date 2014年1月4日下午5:55:31
	 */
	private void loadDataFromNet(int page) {
		final boolean isRefreshFromTop = page == 1;
		if (!mPullToRefreshAttacher.isRefreshing() && isRefreshFromTop) {
			mPullToRefreshAttacher.setRefreshing(true);
		}
		try {
			RequestManager.addRequest(
					new GsonRequest<Food.FoodsRequestData>(
											String.format(HappyGyApi.FOODS_LIST,
											URLEncoder.encode(foodName, "utf-8"), page),	
					Food.FoodsRequestData.class,
					null, 
					new LoadSucessListener(page, isRefreshFromTop),
					new ErrorListener() {
						public void onErrorResponse(VolleyError data) {
							Toast.makeText(FoodsActivity.this, R.string.refresh_list_failed,
									Toast.LENGTH_SHORT).show();
							
							if (isRefreshFromTop) {
								mPullToRefreshAttacher.setRefreshComplete();
							} else {
								mLoadingFooter.setState(LoadingFooter.State.Idle,
										3000);
							}
						}
					}), this);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	OnItemClickListener itemClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View view,
				int position, long id) {
			
			View v = view.findViewById(R.id.food_info);
			if (v.getVisibility() == View.GONE) {
				v.setVisibility(View.VISIBLE);
				Food food = foodAdapter.getItem(position - foodListView.getHeaderViewsCount());
				TextView daohangText = (TextView) view.findViewById(R.id.daohang);
				TextView zufanjuText = (TextView) view.findViewById(R.id.zufanju);
				TextView bohaoText = (TextView) view.findViewById(R.id.bohao);
				TextView fenxiangText = (TextView) view.findViewById(R.id.fenxiang);
	
				daohangText.setTag(food);
				bohaoText.setTag(food.tel);
				fenxiangText.setTag(food);
				zufanjuText.setTag(food);
				
				daohangText.setOnClickListener(daohangListener);
				zufanjuText.setOnClickListener(zufanjuListener);
				bohaoText.setOnClickListener(bohaoListener);
				fenxiangText.setOnClickListener(fenxiangListener);
			} else {
				v.setVisibility(View.GONE);
			}
		}
	};
	
	
	OnClickListener daohangListener = new OnClickListener() {
		public void onClick(View v) {
			Food food = (Food) v.getTag();
			if (food != null && !"".equals(food.address.trim())) {
				Intent intent = new Intent(FoodsActivity.this,
						MyMapActivity.class);
				intent.putExtra(Global.ADDRESS, food.address);
				intent.putExtra(Global.NAME, food.name);
				startActivity(intent);
			}
		}
	};
	OnClickListener zufanjuListener = new OnClickListener() {
		public void onClick(View v) {
			Food food = (Food) v.getTag();
			String info = "饭局喜讯:【" + food.name + "】,位置在" + food.address
					+ ",餐厅电话：" + food.tel + "。此短信由#玩转广元#系统编辑发送!";
			if (info != null && !"".equals(info.trim())) {
				Intent it = new Intent(Intent.ACTION_VIEW);
				it.putExtra("sms_body", info);
				it.setType("vnd.android-dir/mms-sms");
				startActivity(it);
			}
		}
	};

	OnClickListener bohaoListener = new OnClickListener() {
		public void onClick(View v) {
			String tel = v.getTag().toString();
			if (tel == null || "".equals(tel.trim())) {
				Toast.makeText(FoodsActivity.this, "对不起，暂无电话号码",
						Toast.LENGTH_SHORT).show();
				return;
			}
			String[] tels = tel.split(",");
			if (tels.length != 0) {
				Intent intent = new Intent(Intent.ACTION_DIAL,
						Uri.parse("tel://" + tels[0]));
				startActivity(intent);
			} else {
				Toast.makeText(FoodsActivity.this, "对不起，暂无电话号码",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	OnClickListener fenxiangListener = new OnClickListener() {
		public void onClick(View v) {
			Food food = (Food) v.getTag();

			// 快捷分享
			OnekeyShare oks = new OnekeyShare();
			oks.setNotification(R.drawable.ic_launcher, "Gtpass");
			String info = "刚刚发现#"+food.name+"#，推荐吃货们去试试哟。地址："+food.address+"；电话："+food.tel+"。【餐厅分享来自玩转广元 】";
			oks.setText(info);
			oks.setSilent(false);
			oks.show(FoodsActivity.this);
		}
	};

	
	//列表滚动事件回调
	OnScrollListener foodScrollListener = new OnScrollListener() {
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			
		}
		
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			if (mLoadingFooter.getState() == LoadingFooter.State.Loading
					|| mLoadingFooter.getState() == LoadingFooter.State.TheEnd) {
				 mLoadingFooter.setState(LoadingFooter.State.Idle, 3000);
				return;
			}
			if (firstVisibleItem + visibleItemCount >= totalItemCount
					&& totalItemCount != 0
					&& totalItemCount != foodListView.getHeaderViewsCount()
							+ foodListView.getFooterViewsCount()
					&& foodAdapter.getCount() > 0) {
				loadNextPage();
			}
		}
	};
	
	
	/**
	 * 
	 * @description 加载下一页
	 *
	 * @author ChengBin
	 * @date   2014年1月5日下午4:09:53
	 */
	private void loadNextPage() {
		mLoadingFooter.setState(LoadingFooter.State.Loading);
		loadDataFromNet(mPage + 1);
	}
	
	

	@Override
	public void onRefreshStarted(View view) {
		loadFirstPage();
	}
	
	private final class LoadSucessListener implements Response.Listener<Food.FoodsRequestData> {

		private int page;
		private boolean isRefreshFromTop;
		
		public LoadSucessListener(int page, boolean isRefreshFromTop) {
			this.page = page;
			this.isRefreshFromTop = isRefreshFromTop;
		}
		
		@Override
		public void onResponse(final FoodsRequestData requestData) {
			CommonUtils.executeAsyncTask(new AsyncTask<Object, Object, Object>(){
				protected Object doInBackground(Object... params) {
					if (requestData.getFoods().size() > 0) {
						mPage = page;
						if (mPage == 1) {
							foodsDateHelper.deleteAll();
							System.out.println("del");
						}
						ArrayList<Food> foods = requestData.getFoods();
						foodsDateHelper.bulkInsert(foods);
					}
					return null;
				}
				
				 @Override
                 protected void onPostExecute(Object o) {
                     super.onPostExecute(o);
                    if (isRefreshFromTop) {
                         mPullToRefreshAttacher.setRefreshComplete();
                     } else {
                         mLoadingFooter.setState(LoadingFooter.State.Idle, 3000);
                     }
                 }
				
			});
		}
		
	}

}
